package com.weimuu.demo

import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowFactory
import com.intellij.ui.content.ContentFactory
import com.intellij.ui.jcef.JBCefBrowser
import com.intellij.util.ui.UIUtil
import org.cef.browser.CefBrowser
import org.cef.browser.CefFrame
import org.cef.handler.CefLoadHandlerAdapter
import org.cef.handler.CefLifeSpanHandlerAdapter
import java.awt.BorderLayout
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import javax.swing.JButton
import javax.swing.JPanel
import javax.swing.UIManager
import javax.swing.event.ChangeEvent
import javax.swing.event.ChangeListener

class JCEFSidebarConfig : ToolWindowFactory {

    private val BASE_URL = "https://www.zhihu.com"
    private lateinit var browser: JBCefBrowser
    // 记录上一次主题状态，避免重复刷新
    private var lastIsDarkTheme: Boolean = UIUtil.isUnderDarcula()

    override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) {
        val targetUrl = getThemeAwareUrl()
        browser = JBCefBrowser(targetUrl)

        val panel = JPanel(BorderLayout())

        val btnBack = JButton("←").apply {
            isEnabled = false
            addActionListener { browser.cefBrowser.goBack() }
        }

        val btnForward = JButton("→").apply {
            isEnabled = false
            addActionListener { browser.cefBrowser.goForward() }
        }

        val btnRefresh = JButton("⟳").apply {
            addActionListener { browser.cefBrowser.reload() }
        }

        val buttonPanel = JPanel().apply {
            add(btnBack)
            add(btnForward)
            add(btnRefresh)
        }

        panel.add(buttonPanel, BorderLayout.NORTH)
        panel.add(browser.component, BorderLayout.CENTER)

        // 新窗口打开时添加主题参数（保持不变）
        browser.jbCefClient.addLifeSpanHandler(object : CefLifeSpanHandlerAdapter() {
            override fun onBeforePopup(
                cefBrowser: CefBrowser,
                cefFrame: CefFrame,
                targetUrl: String,
                targetFrameName: String
            ): Boolean {
                val themedTargetUrl = addThemeParameter(targetUrl)
                cefBrowser.executeJavaScript(
                    "window.location.href = '$themedTargetUrl';",
                    cefBrowser.url,
                    0
                )
                return true
            }
        }, browser.cefBrowser)

        // 加载状态更新按钮（保持不变）
        browser.jbCefClient.addLoadHandler(object : CefLoadHandlerAdapter() {
            override fun onLoadingStateChange(
                browser: CefBrowser,
                isLoading: Boolean,
                canGoBack: Boolean,
                canGoForward: Boolean
            ) {
                UIUtil.invokeLaterIfNeeded {
                    btnBack.isEnabled = canGoBack
                    btnForward.isEnabled = canGoForward
                }
            }
        }, browser.cefBrowser)

        // 右键隐藏窗口（保持不变）
        panel.addMouseListener(object : MouseAdapter() {
            override fun mouseClicked(e: MouseEvent) {
                if (e.button == MouseEvent.BUTTON3) {
                    val browserBounds = browser.component.bounds
                    val clickPoint = e.point
                    if (!browserBounds.contains(clickPoint)) {
                        toolWindow.hide(null)
                    }
                }
            }
        })

        // 🔥 替换为低版本兼容的主题监听方案（核心修改）
        registerLowVersionThemeChangeListener()

        // 添加到工具窗口（保持不变）
        toolWindow.contentManager.addContent(
            ContentFactory.getInstance().createContent(panel, "", false)
        )
    }

    /**
     * 低版本兼容：监听 LookAndFeel 变化（主题切换会触发）
     */
    private fun registerLowVersionThemeChangeListener() {
        // 监听 UIManager 的 LookAndFeel 属性变化
        UIManager.addPropertyChangeListener { event ->
            if (event.propertyName == "lookAndFeel") { // 仅关注主题相关变化
                UIUtil.invokeLaterIfNeeded { // 确保在 UI 线程执行
                    val currentIsDarkTheme = UIUtil.isUnderDarcula()
                    // 只有主题真的变化了，才刷新 URL（避免重复加载）
                    if (currentIsDarkTheme != lastIsDarkTheme) {
                        lastIsDarkTheme = currentIsDarkTheme
                        val newUrl = getThemeAwareUrl()
                        browser.loadURL(newUrl) // 同步切换知乎主题
                    }
                }
            }
        }
    }

    /**
     * 根据当前主题生成 URL（保持不变）
     */
    private fun getThemeAwareUrl(): String {
        val themeParam = if (UIUtil.isUnderDarcula()) "dark" else "light"
        return "$BASE_URL?theme=$themeParam"
    }

    /**
     * 给 URL 添加主题参数（保持不变）
     */
    private fun addThemeParameter(url: String): String {
        val themeParam = if (UIUtil.isUnderDarcula()) "theme=dark" else "theme=light"
        return when {
            url.contains("?") -> "$url&$themeParam"
            else -> "$url?$themeParam"
        }
    }

}
